package com.sky.aspect;

import com.sky.annotation.AutoFill;
import com.sky.constant.AutoFillConstant;
import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.time.LocalDateTime;

/**
 * 自定义切面类,用于实现某些方法公共代码填充
 */
@Aspect
@Component
@Slf4j
public class AutoFillAspect {
    @Pointcut
    private void autoFillPointCut(){}
    @Before("execution(* com.sky.mapper.*.*(..)) && @annotation(com.sky.annotation.AutoFill)")
    public void autoFill(JoinPoint joinPoint){
        log.info("正在填充公共字段....");
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        //获取注解的值
        OperationType value = signature.getMethod().getAnnotation(AutoFill.class).value();
        //获取方法参数的值
        Object[] args = joinPoint.getArgs();
        if (null == args || args.length == 0) {
            return;
        }
        Object object = args[0];

        Class<?> clazz = object.getClass();
        Long currentId = BaseContext.getCurrentId();
        LocalDateTime now = LocalDateTime.now();
        try {
            Method setUpdateTime = clazz.getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
            Method setUpdateUser = clazz.getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);
            Method setCreateTime = clazz.getDeclaredMethod(AutoFillConstant.SET_CREATE_TIME, LocalDateTime.class);
            Method setCreateUser = clazz.getDeclaredMethod(AutoFillConstant.SET_CREATE_USER, Long.class);
            setUpdateTime.invoke(object, now);
            setUpdateUser.invoke(object, currentId);
            if (value.equals(OperationType.INSERT)) {
                setCreateTime.invoke(object, now);
                setCreateUser.invoke(object, currentId);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
